const router = require("express").Router();
const bcrypt = require("bcryptjs"); //密码解密
const jwt = require("jsonwebtoken"); // 对jwt数据进行加密处理
const User = require("../model/user");
const { SECRET, EXPIRESD } = require("../util/private");
const { getLoginUserFromJWT } = require("../util/tools");

// 注册;
router.post("/register", async (req, res) => {
  const user = new User(req.body); //实例化user数据
  // 注册之前进行判断，数据库里是否已存在此用户
  const isUsername = await User.findOne({
    username: req.body.username,
  });
  if (!isUsername) {
    const result = await user.save(); //注册用户
    console.log(result);
    // res.send(result);
    //判断是否插入数据成功
    if (result) {
      res.json({
        code: 200,
        msg: "注册成功",
        users: result,
      });
    } else {
      res.json({
        code: 403,
        msg: "注册失败",
      });
    }
  } else {
    res.json({
      code: 403,
      msg: "用户名已经存在",
    });
  }
});

//登录
router.post("/login", async (req, res) => {
  //判断是否有此用户信息
  const user = await User.findOne({
    username: req.body.username,
  });
  if (!user) {
    res.json({
      code: 403,
      msg: "用户名不存在",
    });
  }
  //比较密码的正确性
  const isPasswordValid = bcrypt.compareSync(req.body.password, user.password);
  if (!isPasswordValid) {
    res.json({
      code: 403,
      msg: "密码不正确",
    });
  }
  //生成token 根据token判断对应的是数据库中的哪个用户
  // 拿到数据库里的用户id
  const token = jwt.sign(
    {
      uid: String(user._id), //数据库中用户的id
    },
    SECRET,
    { expiresIn: EXPIRESD }
  );
  res.json({
    code: 200,
    msg: "登录成功",
    user,
    token,
  });
});

// 查询所有用户
router.get("/users", async (req, res) => {
  const users = await User.find();
  // res.send(users);
  if (users) {
    res.json({
      code: 200,
      msg: "用户列表获取成功",
      users,
    });
  }
});

//获取用户信息
router.get("/profile", async (req, res, next) => {
  try {
    //验证解密用户的id
    const uid = getLoginUserFromJWT(req);
    req.user = await User.findById(uid);
    if (req.user) {
      res.json({
        code: 200,
        msg: "获取用户信息成功",
        user: req.user,
      });
    } else {
      res.json({
        code: 403,
        msg: "获取用户信息失败",
      });
    }
  } catch (err) {
    next(err);
  }
});

module.exports = router;
